/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-07-01 14:32:59
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal } from 'antd';
import { TransferReducer } from '../reducers/TransferReducer';
import { ADD_TRANSFER, DELETE_TRANSFER, EDIT_TRANSFER, SET_TRANSFER_LIST } from '../constants';
import { addTransfer, deleteTransfer, editTransfer, fetchTransferListByPage } from '@/api/transfer';

const initialState = {
  // 当前选中的项目
  transferState: 0,
  // 选中的表格条目
  selectItems: [],
  // 移交申请单列表
  transferList: []
};

const TransferContext = createContext();

const TransferContextProvider = (props) => {
  const [state, dispatch] = useReducer(TransferReducer, initialState);

  const actions = {
    /**
     * @description: 获取移交清单列表
     */
    getTransferList(params) {
      return new Promise((resolve, reject) => {
        fetchTransferListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_TRANSFER_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    addTransferFunc(params) {
      return new Promise((resolve, reject) => {
        addTransfer(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_TRANSFER, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    editTransferFunc(params) {
      return new Promise((resolve, reject) => {
        editTransfer(params)
          .then((res) => {
            const { data } = res;
            const { id } = res.data;
            dispatch({ type: EDIT_TRANSFER, id, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    delTransferFunc(id, content = '确认删除选中的移交清单？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteTransfer(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_TRANSFER, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  // watch listQuery来加载排序列表
  useEffect(() => {}, []);

  return (
    <TransferContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </TransferContext.Provider>
  );
};

export const useTransferContext = () => {
  return useContext(TransferContext);
};

export { TransferContext, TransferContextProvider };
